import { useEffect, useState } from "react"; 
import { invoke } from "@tauri-apps/api/tauri";
import "./App.css";
import Editor from "./components/Editor";
import TitleBar from "./components/TitleBar"; 
import TreeFile from "./components/TreeFile" 

 
 

 


function getStorage(key: string): string | null {
  try {
    return window.localStorage.getItem(key);
  } catch (error) {
    console.error("获取 localStorage 失败:", error);
    return null;
  }
}

// @ts-ignore
function setStorage(key: string, value: string): void {
  try {
    window.localStorage.setItem(key, value);
  } catch (error) {
    console.error("设置 localStorage 失败:", error);
  }
}

function App() { 
  const [isShow, setIsShow] =  useState<boolean>(true);
  const [fileType, setFileType] =  useState<string>("md");
  const [fileName, setFileName] = useState<string>("");
  const [content, setContent] = useState<any>( );
  const [filePath, setFilePath] = useState<string>("");
  const [screenHeight, setScreenHeight] = useState(window.innerHeight);

    // 监听窗口大小变化
    useEffect(() => {
      const handleResize = () => {
        setScreenHeight(window.innerHeight);
      };
  
      window.addEventListener('resize', handleResize);
  
      // 清理事件监听
      return () => {
        window.removeEventListener('resize', handleResize);
      };
    }, []);
    
const hadleSide = (bool:boolean) => {
  const result:any = getStorage("filePath") 
  setFilePath(result);
  setIsShow(bool); 
}

const setFileContent=  async (data:any)=>{
  if(  data && filePath){   
    await invoke("write_file_content", { path: filePath, content: data });
  }
}

// @ts-ignore
const onReadFile = (data)=>{ 
 // @ts-ignore
 setFileName(data.fileName)
 setFileType(data.type)
 // @ts-ignore
 setFilePath(data.path||"" ); 
 setContent("")
  setTimeout(() => {
   setContent(data.content)
  },100)
}

const onDeleteRefresh = ()=>setContent("")
const contentHeight = `${screenHeight - 74.5}px`;
console.log(`screenHeight: ${contentHeight}px`);

  return (  
    <div className="Layout w-99vw h-screen  ">
         <div className="Header   border-b-2 border-gray-300"> 
           <TitleBar side={hadleSide} title={fileName} /> 
         </div>
       <div className="Content w-full   flex" style={{ height: contentHeight }}>
        {
           isShow&& <div className="Sider w-2/6 max-w-64 mt-2 mb-2 pl-2 pr-2 border-r border-gray-300 ">
            <TreeFile onDeleteRefresh={onDeleteRefresh} onReadFile={(data) => onReadFile(data)} />
           </div>
        }

        <div className="Content w-full h-full relative overflow-hidden overflow-y-auto">
        {
        content && <Editor onChange={(data)=>setFileContent(data)} type={fileType} content={content} /> 
      } 
        </div> 
       </div>
       <div className="Footer h-5 border-t-2 border-gray-300  m-0">

       </div>
    </div>
  );


}

export default App;
